package com.chaos.meta.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;

/**
 * @author naicha
 * @date 2020/7/9 11:53
 * @description: String Handle
 */
@Slf4j
public final class StringUtil {
    private StringUtil(){
    }

    private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString="INVALID";
    static {
        String[] keyStr = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    /**
     * 防xss攻击
     */
    public static String cleanXSS(String valueBefore) {
        String valueAfter = valueBefore.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        valueAfter = valueAfter.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        valueAfter = valueAfter.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        valueAfter = valueAfter.replaceAll("'", "& #39;");
        valueAfter = valueAfter.replaceAll("eval\\((.*)\\)", "");
        valueAfter = valueAfter.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        valueAfter = valueAfter.replaceAll("script", "");
        return valueAfter;
    }

    /**
     * 防sql注入
     */
    public static String cleanSqlKeyWords(String valueBefore) {
        String valueAfter = valueBefore;
        for (String keyword : notAllowedKeyWords) {
            if (valueAfter.length() > keyword.length() + 4
                    && (valueAfter.contains(" "+keyword)||valueAfter.contains(keyword+" ")||valueAfter.contains(" "+keyword+" "))) {
                valueAfter = StringUtils.replace(valueAfter, keyword, replacedString);
            }
        }
        return valueAfter;
    }
    
    /**
     * AVM中的名称用于自动生成代码，限定只能由字母和数字组成。因为生成变量名还要加前缀，所以允许首字符是数字。
     * @param name
     * @return
     */
    public static boolean isVariableNameAllowed(final String name) {
    	int length = name.length();
    	if(length == 0) {
    		return false;
    	}
    	
    	for(int i = 0; i < length; i++) {
    		char c = name.charAt(i);
    		if(!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')) {
    			return false;
    		}
    	}
    	return true;
    }
    
    public static String digestPassword( String userName, String inputPassword) {
    	return DigestUtils.md5DigestAsHex((userName.toLowerCase()+inputPassword).getBytes());
    }

    public static String generateRandomString(int length)
    {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            StringBuffer sb = new StringBuffer();
            for(int i=0; i<length; i++)
            {
                sb.append(String.valueOf(random.nextInt(10)));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("fail to generateRandomString, the detail is:" + e);
            return null;
        }
    }

    public static String encodeFileName(String fileNames, HttpServletRequest request) {
        String codedFilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident") ||
                    null != agent && -1 != agent.indexOf("Edge")) {
                // ie浏览器及Edge浏览器
                String name = URLEncoder.encode(fileNames, "UTF-8");
                codedFilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                // 火狐,Chrome等浏览器
                codedFilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codedFilename;
    }


	static public String genUrl(boolean enabledSsl, String ip, int port, String path) {
		StringBuilder sb = new StringBuilder();
		sb.append(enabledSsl ? "https://" : "http://");
		sb.append(ip);
		if(port != 80) {
			sb.append(":");
			sb.append(port);
		}
		sb.append(path);
        String x = "[备注]：本结果仅对采样负责，如诊断结果有疑问，请于收到报告一周内与病理诊断医生联系，谢谢合作！\n" +
                "[备注]：本结果仅对采样负责，如诊断结果有疑问，请于收到报告一周内与病理诊断医生联系，谢谢合作！\n" +
                "[备注]：本结果仅对采样负责，如诊断结果有疑问，请于收到报告一周内与病理诊断医生联系，谢谢合作！\n" +
                "[备注]：本结果仅对采样负责，如诊断结果有疑问，请于收到报告一周内与病理诊断医生联系，谢谢合作！";
		return sb.toString(); 
	}
}